<template>
  <div class="page-container">
    <div class="page-header">
      <div class="header-title">
        <h2>{{ headerTitle }}</h2>
      </div>
      <div class="header-actions">
        <a-space>
          <a-radio-group v-model:value="editPermission">
            <a-radio :value="true">可编辑</a-radio>
            <a-radio :value="false">不可编辑</a-radio>
          </a-radio-group>
          <a-button v-if="type !== 'view'" type="primary" :loading="btnLoading" @click="handleSubmit">提交</a-button>
          <a-button v-if="type !== 'view'" type="primary" @click="modify">测试单元格赋值</a-button>
          <a-button @click="goBack">返回</a-button>
        </a-space>
      </div>
    </div>

    <div class="page-content">
      <div class="content-wrapper">
        <div ref="container" class="univer-container"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { createUniver, defaultTheme, LocaleType, Tools } from '@univerjs/presets';
  import '@univerjs/presets/lib/styles/preset-docs-collaboration.css';
  import '@univerjs/presets/lib/styles/preset-docs-core.css';
  import '@univerjs/presets/lib/styles/preset-docs-drawing.css';
  import '@univerjs/presets/lib/styles/preset-docs-hyper-link.css';
  import '@univerjs/presets/lib/styles/preset-docs-thread-comment.css';
  import '@univerjs/presets/lib/styles/preset-sheets-advanced.css';
  import '@univerjs/presets/lib/styles/preset-sheets-collaboration.css';
  import '@univerjs/presets/lib/styles/preset-sheets-conditional-formatting.css';
  import '@univerjs/presets/lib/styles/preset-sheets-core.css';
  import '@univerjs/presets/lib/styles/preset-sheets-data-validation.css';
  import '@univerjs/presets/lib/styles/preset-sheets-drawing.css';
  import '@univerjs/presets/lib/styles/preset-sheets-filter.css';
  import '@univerjs/presets/lib/styles/preset-sheets-find-replace.css';
  import '@univerjs/presets/lib/styles/preset-sheets-hyper-link.css';
  import '@univerjs/presets/lib/styles/preset-sheets-sort.css';
  import '@univerjs/presets/lib/styles/preset-sheets-thread-comment.css';
  import {
    CopySheetCommand,
    RangeProtectionPermissionEditPoint,
    RangeProtectionPermissionViewPoint,
    WorkbookCreateSheetPermission,
    WorkbookEditablePermission,
    WorkbookManageCollaboratorPermission,
  } from '@univerjs/presets/preset-sheets-core';

  import { UniverSheetsCorePreset } from '@univerjs/presets/preset-sheets-core';
  import sheetsCoreZhCN from '@univerjs/presets/preset-sheets-core/locales/zh-CN';
  import { message } from 'ant-design-vue';
  import { onBeforeUnmount, onMounted, ref } from 'vue';
  import { useRoute } from 'vue-router';
  import { getProtectedRanges, getWorkbookDataStore, updateWorkbookData } from './data';

  const route = useRoute();
  const type = ref(route.query.type);
  const container = ref(null);
  const univerInstance = ref(null);
  const btnLoading = ref(false);
  const headerTitle = ref('Excel操作');
  const currentCell = ref(null);
  const workbookDataStore = getWorkbookDataStore();
  const editPermission = ref(true);

  // 存储 Univer 实例
  const univerRef = {
    value: null,
  }

  onMounted(async () => {
    // 设置页面标题
    switch (type.value) {
      case 'design':
        headerTitle.value = '设计Excel模板';
        break;
      case 'modify-template':
        headerTitle.value = '修改Excel模板';
        break;
      case 'fill':
        headerTitle.value = 'Excel模板填写';
        break;
      case 'view':
        headerTitle.value = '查看Excel';
        break;
    }
    const { univerAPI, univer } = createUniver({
      locale: LocaleType.ZH_CN,
      locales: {
        zhCN: Tools.deepMerge({}, sheetsCoreZhCN),
      },
      theme: defaultTheme,
      presets: [
        UniverSheetsCorePreset({
          container: container.value,
          contextMenu: type.value !== 'view',
          footer: ['design', 'modify-template'].includes(type.value),
          header: ['design', 'modify-template'].includes(type.value),
          menu: {
            [CopySheetCommand.id]: {
              hidden: true,
            },
          },
        }),
      ],
    });
    univerInstance.value = univerAPI;

    // 存储 Univer 实例
    univerRef.value = univer;

    try {
      if (type.value === 'design') {
        // 创建全新的Excel
        univerAPI.createWorkbook({
          name: '报表',
          sheets: {
            sheet1: {
              id: 'sheet1',
              name: '报表',
            },
          },
        });
      } else {
        // 加载已有的数据
        univerAPI.createWorkbook(workbookDataStore.value);
      }
      // 监听单元格点击
      univerAPI.getActiveWorkbook().onCellClick(cell => {
        currentCell.value = cell;
        console.log('当前点击的单元格:', cell);
      });
      // 暂时不用onBeforeCommandExecute,单页签用不上
      // univerAPI.onBeforeCommandExecute(async command => {
      // const { id } = command;
      // if (id === 'sheet.operation.set-selections') {
      const workbook = univerAPI.getActiveWorkbook();
      const sheet = workbook.getActiveSheet();
      const unitId = workbook.getId();
      const subUnitId = sheet.getSheetId();
      const permission = univerAPI.getPermission();
      // 基础权限设置
      permission.setWorkbookPermissionPoint(unitId, WorkbookCreateSheetPermission, false);
      permission.setWorkbookPermissionPoint(unitId, WorkbookManageCollaboratorPermission, false);
      permission.setPermissionDialogVisible(false);

      if (type.value === 'view') {
        permission.setWorkbookPermissionPoint(unitId, WorkbookEditablePermission, false);
        setTimeout(() => {
          adjustColumnWidth(['A', 'B']);
          getAllColumns();
        }, 500);
        return;
      }
      // 获取保护区域数据
      const ranges = getProtectedRanges(subUnitId);
      if (ranges.length > 0) {
        const { permissionId } = await permission.addRangeBaseProtection(unitId, subUnitId, ranges);
        permission.setRangeProtectionPermissionPoint(unitId, subUnitId, permissionId, RangeProtectionPermissionViewPoint, true);
        permission.setRangeProtectionPermissionPoint(
          unitId,
          subUnitId,
          permissionId,
          RangeProtectionPermissionEditPoint,
          ['design', 'modify-template'].includes(type.value)
        );
      }
      // }
      // });
    } catch (error) {
      console.error('Excel初始化错误:', error);
    }
  });
  // 销毁实例
  onBeforeUnmount(() => {
    // if (univerInstance.value) {
    //   const activeWorkbook = univerInstance.value.getActiveWorkbook();
    //   const unitId = activeWorkbook && activeWorkbook.getId();
    //   if (unitId) {
    //     univerInstance.value.dispose(unitId);
    //   }
    // }

    // 使用 univer 实例的 dispose 方法销毁实例，不要使用 univerAPI 的 disposeUnit 方法
    univerRef.value.dispose();
  });

  const handleSubmit = async () => {
    try {
      btnLoading.value = true;
      const workbook = univerInstance.value.getActiveWorkbook();
      const savedData = workbook.save();
      console.log('保存的数据:', savedData);
      updateWorkbookData(savedData);
      message.success('保存成功');
      goBack();
    } catch (error) {
      console.error('操作失败：', error);
      message.error('保存失败');
    } finally {
      btnLoading.value = false;
    }
  };

  const modify = () => {
    if (!currentCell.value) {
      currentCell.value = {
        overflowLocation: {
          row: 0,
          col: 0,
        },
      };
    }
    const sheet = univerInstance.value.getActiveWorkbook().getActiveSheet();
    const { row, col } = currentCell.value.overflowLocation;
    const range = sheet.getRange(row, col);
    if (editPermission.value) {
      range.setValue({
        v: 'Hello, Univer',
        custom: {
          fill: true,
        },
      });
    } else {
      range.setValue('哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈');
    }
  };
  function adjustColumnWidth(columns = []) {
    const workbook = univerInstance.value.getActiveWorkbook();
    const sheet = workbook.getActiveSheet();
    columns.forEach(col => {
      const colIndex = col.charCodeAt(0) - 'A'.charCodeAt(0);
      let maxLength = 0;
      for (let row = 1; row <= 1000; row++) {
        const cell = sheet.getRange(`${col}${row}`);
        let contentLength = 0;
        const richTextValue = cell.getRichTextValue();

        // 判断字符是否为中文
        const isChineseChar = char => /[\u4e00-\u9fa5]/.test(char);

        // 计算字符串长度（中文字符计1，非中文字符计1/2）
        const calculateLength = text => {
          // 将非字符串类型转换为字符串
          const str = String(text);
          let chineseLength = 0;
          let nonChineseLength = 0;

          for (let char of str) {
            if (isChineseChar(char)) {
              chineseLength++;
            } else {
              nonChineseLength++;
            }
          }

          return chineseLength + Math.ceil(nonChineseLength / 2);
        };

        if (richTextValue) {
          const text = richTextValue._data.body.dataStream;
          contentLength = calculateLength(text);
        } else {
          const cellValue = cell.getValue();
          if (cellValue) {
            contentLength = calculateLength(cellValue);
          }
        }

        if (contentLength > maxLength) {
          maxLength = contentLength;
        }
      }
      const estimatedWidth = Math.max(maxLength * 18, 100);
      sheet.setColumnWidth(colIndex, estimatedWidth);
    });
  }
  function getAllColumns() {
    // Get the active workbook and sheet
    const workbook = univerInstance.value.getActiveWorkbook();
    const sheet = workbook.getActiveSheet();

    // Get max columns
    const maxColumns = sheet.getMaxColumns();

    // Function to convert column index to letter
    function columnToLetter(column) {
      let temp,
        letter = '';
      while (column > 0) {
        temp = (column - 1) % 26;
        letter = String.fromCharCode(temp + 65) + letter;
        column = (column - temp - 1) / 26;
      }
      return letter;
    }

    // Create array of column letters
    const columns = [];
    for (let i = 1; i <= maxColumns; i++) {
      columns.push(columnToLetter(i));
    }

    // Log the columns
    console.log(`Sheet has ${maxColumns} columns: ${columns.join(', ')}`);

    return columns;
  }
  const goBack = () => {
    window.history.back();
  };
</script>

<style scoped>
  .page-container {
    min-height: 100vh;
    background-color: #f0f2f5;
    display: flex;
    flex-direction: column;
  }

  .page-header {
    background: #fff;
    padding: 16px 24px;
    box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .header-title h2 {
    margin: 0;
    color: rgba(0, 0, 0, 0.85);
    font-weight: 600;
    font-size: 20px;
  }

  .header-actions {
    display: flex;
    align-items: center;
  }

  .page-content {
    flex: 1;
    padding: 24px;
    display: flex;
    justify-content: center;
  }

  .content-wrapper {
    width: 80%;
    background: #fff;
    border-radius: 2px;
    box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  }

  .univer-container {
    width: 100%;
    height: calc(100vh - 180px);
    min-height: 500px;
  }

  :deep(.ant-btn) {
    margin-left: 8px;
  }

  :deep(.ant-space) {
    gap: 8px !important;
  }

  :deep(.ant-radio-group) {
    margin-right: 16px;
  }
</style>
